package cn.tedu.florist.controller;


import cn.tedu.florist.mapper.UserMapper;
import cn.tedu.florist.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    /*查看是否注册过*/
    @RequestMapping("/selectByPhone")
    public int selectByPhone(User user){
        System.out.println("user = " + user);
        //通过用户输入的用户名查询到数据库中的信息
        User u=mapper.select(user.getPhone());
        //用户名已存在 结束流程
        if (u!=null){
            return 2;
        }
        //用户不存在  存入数据
        mapper.insert(user);
        //注册成功
        return 1;
    }

    @PostMapping("/user/login")
    public int login(@Validated User user, BindingResult result, HttpSession session){
        if(result.hasErrors()){
            // 获得验证结果中的错误信息(多条错误信息随机获取)
            String msg=result.getFieldError().getDefaultMessage();

        }
        User u=mapper.select(user.getPhone());
        if (u!=null){
             if (u.getPassword().equals(user.getPassword())) {
                 session.setAttribute("users",u);
                 return 1;  //登录成功
             }
             return 2;  //密码错误
        }
        return 3;   //用户不存在
    }

    @GetMapping("/users/session")
    public User checkLogin(HttpSession session){
        return (User)session.getAttribute("users");
    }

    @GetMapping("/user/logout")
    public void logout(HttpSession session){
        session.removeAttribute("users");
    }
}









